package com.zdb.java.thread;

import javax.swing.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

public class ContainerNotSafeDemo {

    public static void main(String[] args) {
//        listNotSafe();
//        setNotSafe();
        mapNotSafe();

        while(Thread.activeCount() > 2) {
            Thread.yield();
        }
    }

    public static void mapNotSafe() {
//        List<String> list = new ArrayList<>();
//        List<String> list = Collections.synchronizedList(new ArrayList<>());
        // 写入时，创建一个新的array,长度为 +1，复制原来array的值，然后再指向新的array,这样只需要在写入时加锁，读取时不需要加锁
//        Map<String, String> map = new HashMap<>();
//        Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
        Map<String, String> map = new ConcurrentHashMap<>();

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                map.put(UUID.randomUUID().toString().substring(0, 8), "");
                System.out.println(map);
            }, "" + i).start();
        }
    }

    public static void setNotSafe() {
//        List<String> list = new ArrayList<>();
//        List<String> list = Collections.synchronizedList(new ArrayList<>());
        // 写入时，创建一个新的array,长度为 +1，复制原来array的值，然后再指向新的array,这样只需要在写入时加锁，读取时不需要加锁
        Set<String> list = new CopyOnWriteArraySet<>();

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, "" + i).start();
        }
    }

    public static void listNotSafe() {
//        List<String> list = new ArrayList<>();
//        List<String> list = Collections.synchronizedList(new ArrayList<>());
        // 写入时，创建一个新的array,长度为 +1，复制原来array的值，然后再指向新的array,这样只需要在写入时加锁，读取时不需要加锁
        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, "" + i).start();
        }
    }
}
